""" -*- coding: utf-8 -*-"""
from datetime import datetime
from file_mg.exts import db


# 关联表
department_codes = db.Table(
    'department_codes',
    db.Column('department_id', db.Integer, db.ForeignKey('department.id'), primary_key=True),
    db.Column('code_id', db.Integer, db.ForeignKey('code.id'), primary_key=True)
)


class Code(db.Model):
    __tablename__ = 'code'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    value = db.Column(db.String(20), nullable=False, unique=True)

    def to_dict(self):
        return {'id': self.id, 'value': self.value}


class Department(db.Model):
    __tablename__ = 'department'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    manager = db.Column(db.String(100), nullable=False)
    phone = db.Column(db.String(20), nullable=False)
    address = db.Column(db.String(200), nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    codes = db.relationship(
        'Code',
        secondary=department_codes,
        lazy='subquery',
        backref=db.backref('departments', lazy=True)
    )

    users = db.relationship('User', backref='department', lazy=True)
    projects = db.relationship('Project', backref='department', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'manager': self.manager,
            'phone': self.phone,
            'address': self.address,
            'created_at': self.created_at.isoformat(),
            'codes': [code.value for code in self.codes]
        }


class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False)
    password_hash = db.Column(db.String(200), nullable=False)
    phone = db.Column(db.String(20), nullable=False)
    email = db.Column(db.String(120), nullable=False, unique=True)
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=False)
    role = db.Column(db.String(50), nullable=False, default='staff')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    created_projects = db.relationship('Project', backref='creator', lazy=True)
    coordinated_projects = db.relationship('Project', backref='coordinator', lazy=True)
    project_progresses = db.relationship('ProjectProgress', backref='user', lazy=True)
    files = db.relationship('File', backref='user', lazy=True)

    def set_password(self, password):
        from werkzeug.security import generate_password_hash
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        from werkzeug.security import check_password_hash
        return check_password_hash(self.password_hash, password)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'phone': self.phone,
            'email': self.email,
            'department_id': self.department_id,
            'department_name': self.department.name if self.department else None,
            'role': self.role,
            'created_at': self.created_at.isoformat()
        }

    def to_dict_with_department(self):
        data = self.to_dict()
        if self.department:
            data['department'] = self.department.to_dict()
        return data


class ProjectType(db.Model):
    __tablename__ = 'project_type'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    description = db.Column(db.String(500))

    projects = db.relationship('Project', backref='project_type', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description
        }


class Project(db.Model):
    __tablename__ = 'project'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(200), nullable=False)
    project_number = db.Column(db.String(50), nullable=False, unique=True)
    department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=False)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    coordinator_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    project_type_id = db.Column(db.Integer, db.ForeignKey('project_type.id'))
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    progresses = db.relationship('ProjectProgress', backref='project', lazy=True)
    files = db.relationship('File', backref='project', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'project_number': self.project_number,
            'department_id': self.department_id,
            'department_name': self.department.name if self.department else None,
            'creator_id': self.creator_id,
            'creator_name': self.creator.name if self.creator else None,
            'coordinator_id': self.coordinator_id,
            'coordinator_name': self.coordinator.name if self.coordinator else None,
            'project_type_id': self.project_type_id,
            'project_type_name': self.project_type.name if self.project_type else None,
            'created_at': self.created_at.isoformat()
        }

    def to_dict_full(self):
        data = self.to_dict()
        if self.department:
            data['department'] = self.department.to_dict()
        if self.creator:
            data['creator'] = self.creator.to_dict()
        if self.coordinator:
            data['coordinator'] = self.coordinator.to_dict()
        if self.project_type:
            data['project_type'] = self.project_type.to_dict()
        return data

    @staticmethod
    def generate_project_number(department_id, selected_code):
        """生成项目编号：年份 + 部门编号 + 序号"""
        from datetime import datetime
        import re

        current_year = datetime.now().strftime("%Y")

        # 查找该部门使用该编号的最大序号
        pattern = re.compile(rf"^{current_year}{re.escape(selected_code)}(\d{{3}})$")
        max_sequence = 0

        # 确保在函数内部导入模型以避免循环依赖
        # from . import Department, Project

        department = Department.query.get(department_id)
        if not department:
            return None

        for proj in department.projects:
            match = pattern.match(proj.project_number)
            if match:
                sequence_num = int(match.group(1))
                if sequence_num > max_sequence:
                    max_sequence = sequence_num

        new_sequence = max_sequence + 1
        return f"{current_year}{selected_code}{new_sequence:03d}"

class ProjectProgress(db.Model):
    __tablename__ = 'project_progress'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    description = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'project_id': self.project_id,
            'project_name': self.project.name if self.project else None,
            'user_id': self.user_id,
            'user_name': self.user.name if self.user else None,
            'description': self.description,
            'created_at': self.created_at.isoformat()
        }


class DesignPhase(db.Model):
    __tablename__ = 'design_phase'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100), nullable=False, unique=True)
    description = db.Column(db.String(500))

    file_types = db.relationship('FileType', backref='design_phase', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'description': self.description
        }


class FileType(db.Model):
    __tablename__ = 'file_type'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    design_phase_id = db.Column(db.Integer, db.ForeignKey('design_phase.id'), nullable=False)
    name = db.Column(db.String(100), nullable=False)
    description = db.Column(db.String(500))

    files = db.relationship('File', backref='file_type', lazy=True)

    def to_dict(self):
        return {
            'id': self.id,
            'design_phase_id': self.design_phase_id,
            'design_phase_name': self.design_phase.name if self.design_phase else None,
            'name': self.name,
            'description': self.description
        }


class File(db.Model):
    __tablename__ = 'file'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    project_id = db.Column(db.Integer, db.ForeignKey('project.id'), nullable=False)
    file_type_id = db.Column(db.Integer, db.ForeignKey('file_type.id'), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    file_path = db.Column(db.String(500), nullable=False)
    original_filename = db.Column(db.String(255), nullable=False)
    uploaded_at = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'id': self.id,
            'project_id': self.project_id,
            'project_name': self.project.name if self.project else None,
            'file_type_id': self.file_type_id,
            'file_type_name': self.file_type.name if self.file_type else None,
            'user_id': self.user_id,
            'user_name': self.user.name if self.user else None,
            'file_path': self.file_path,
            'original_filename': self.original_filename,
            'uploaded_at': self.uploaded_at.isoformat(),
            'download_url': f'/files/download/{self.id}'
        }